const Proxy = require('../../proxy')
const webDataUtil = require('../../util/webDataUtil')
const reqlib = require('app-root-path').require
const AccountMachine = reqlib('/app/analysis/accountMachine')
const BuySellMachine = reqlib('/app/analysis/buySellMachine')

const BtbIndex = Proxy.BtbIndex

// 获取合约账户财务信息
module.exports = async function (params) {
  let query = {}
  if (params && params.code) {
    query.code = params.code.toLocaleUpperCase()
  } else {
    query = {
      status: 1,
      hy_status: 1,
      manual: 0
    }
  }
  // 找出币
  let btbList = await BtbIndex.find(query, {
    sort: '-proportion',
    lean: true
  })
  if (btbList.length === 0) {
    return false
  }
  for (let i = 0; i < btbList.length; i++) {
    const item = btbList[i]
    item.symbol = `${item.code}USDT`
    item.min_qty = item.f_min_qty
    item.max_qty = item.f_max_qty
    item.step_size = item.f_step_size
    item.min_notional = item.f_min_notional
    item.tick_size = item.f_tick_size
  }
  const accountMachine = new AccountMachine({
    btbCount: 10
  })
  await accountMachine.refresh()
  for (let i = 0; i < btbList.length; i++) {
    const btbItem = btbList[i]
    const symbolAccount = accountMachine.getBtbItemAccount(btbItem.symbol)
    const futuresAccount = accountMachine.getFuturesAccount()
    const buySellMachine = new BuySellMachine({
      realBuySell: true,
      btbItem: btbItem,
      symbolAccount,
      futuresAccount,
      BtbIndexProxy: BtbIndex
    })
    btbItem.buySellMachine = buySellMachine
    if (btbItem.buySellMachine.hasPosition) {
      // 有仓位
      btbItem.klineList15m = await webDataUtil.getFuturesKLinesAll({
        name: btbItem.code,
        interval: '15m',
        count: 100
      })
      btbItem.close = btbItem.klineList15m[btbItem.klineList15m.length - 1].close
      await btbItem.buySellMachine.requestCancelStopOrder()
      btbItem.buySellMachine.setClosePositionParams()
      const exResult = await buySellMachine.requestOrder()
      await buySellMachine.requestUpdateBtbModel()
      if (exResult) {
        await buySellMachine.clearBtbPosition()
        // 记录交易记录，放这里不去影响主流程
        await buySellMachine.requestCreateTradeRecord()
      }
    }
  }
  return {}
}
